package com.yycx.module.file.provider.oss.listener;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;

/**
 * 自定义监听类,监听文件上传进度
 *
 * @author zyf
 */
@Slf4j
public class PutObjectProgressListener implements ProgressListener {
    private long bytesWritten = 0;
    private long totalBytes = -1;
    private boolean succeed = false;
    private HttpSession session;
    private int percent = 0;

    /**
     * 构造方法中加入session
     */
    public PutObjectProgressListener() {
    }

    public PutObjectProgressListener(HttpSession mSession) {
        this.session = mSession;
        session.setAttribute("upload_percent", percent);
    }

    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                log.debug("开始上传......");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                log.debug("分片大小" + this.totalBytes / (1024 * 1024) + "MB,上传到OSS");
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                    //将进度percent放入session中 官网demo中没有放入session这一步
                    log.debug(bytesWritten / (1024) + " KB 已上传, 上传进度: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                } else {
                    System.out.println(bytes + "已上传,上传进度:" + "(" + this.bytesWritten + "/...)");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                System.out.println("上传成功,共传输" + this.bytesWritten / (1024 * 1024) + "MB");
                break;
            case TRANSFER_FAILED_EVENT:
                System.out.println("上传失败," + this.bytesWritten + "字节已传输");
                break;
            default:
                break;
        }
    }

    public boolean isSucceed() {
        return succeed;
    }

}
